package com.tanhua.sso.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.tanhua.common.enums.SexEnum;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.User;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.common.service.PicUploadService;
import com.tanhua.common.vo.PicUploadResult;
import com.tanhua.sso.service.FaceEngineService;
import com.tanhua.sso.service.UserInfoService;
import com.tanhua.sso.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Map;

@Service
public class UserInfoServiceImpl implements UserInfoService {
    @Autowired
    private UserService userService;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private PicUploadService picUploadService;
    @Autowired
    private FaceEngineService faceEngineService;

    @Override
    public boolean saveUserInfo(Map<String, String> param, String token) {
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
//        封装user的信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getId());
        userInfo.setCity(param.get("city"));
        userInfo.setBirthday(param.get("birthday"));
        userInfo.setNickName(param.get("nickname"));
        userInfo.setSex(param.get("gender").equalsIgnoreCase("man") ? SexEnum.MAN : SexEnum.WOMAN);
//        调用mapper储存消息
        int insert = this.userInfoMapper.insert(userInfo);
        return insert > 0;
    }

    @Override
    public boolean saveUserLogo(MultipartFile file, String token) {
        User user = this.userService.queryUserByToken(token);
        if (null == user) {
            return false;
        }
        try {
            boolean b = this.faceEngineService.checkIsPortrait(file.getBytes());
            if (!b) {
                return false;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        PicUploadResult upload = picUploadService.upload(file);
        if (StringUtils.isEmpty(upload.getName())) {
            return false;
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setCoverPic(upload.getName());
        userInfo.setLogo(upload.getName());

        UpdateWrapper<UserInfo> wrapper = new UpdateWrapper<>();
        wrapper.eq("user_id", user.getId());

        return userInfoMapper.update(userInfo, wrapper) > 0;
    }
}
